package com.wanglin.connect2bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import android.view.KeyEvent.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.wandersnail.bluetooth.BTManager
import cn.wandersnail.bluetooth.ConnectCallback
import cn.wandersnail.bluetooth.Connection
import cn.wandersnail.bluetooth.EventObserver


class MainActivity : AppCompatActivity(), EventObserver {
    companion object {
        private const val TAG = "MainActivity"
        private const val BARCODE_SCANNER_HID = "BarCode Scanner HID"
        private const val BARCODE_SCANNER_HID0581 = "HID 0581"
        private val barCode = StringBuffer()

        //使用正则表达式验证医废袋(盒)编号是否符合规则，如果不符合，将不回调
        //医疗废物编号：15位数字，
        //第1位代表一级分类：1-感染性废物，2-病理性废物， 3-损伤性废物，4-药物性废物，5-化学性废物；
        //第2位代表类型：1-转运箱，2-自动袋子，3-人工袋子，4-利器盒，5-固有容器；
        //第3位代表生产厂家。
        //4-15位共12位数字作为顺序码。
        private val regex =
            "^(http://www\\.ruiyouyiliao\\.com/RFYF/\\?id=)[1-5][2-5][0-9][0-9]{12}$".toRegex()


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //重置
        resetInput()
        //获得已经配对过的蓝牙设备列表
        connPairedBlEs()


    }

    private fun resetInput() {
        findViewById<Button>(R.id.btn_reset).setOnClickListener {
            findViewById<TextView>(R.id.textview_wasteNo).text = ""
            findViewById<TextView>(R.id.textview_weight).text = ""
            findViewById<TextView>(R.id.textview_amount).text = ""
        }
    }

    private fun connPairedBlEs() {
        if (BluetoothAdapter.getDefaultAdapter().enable()) {
            val pairedBlEs = BluetoothAdapter.getDefaultAdapter().bondedDevices
            if (pairedBlEs.isEmpty()) {
                Log.d(
                    TAG,
                    "请先进行蓝牙配对"
                )
            }
            pairedBlEs.forEach { bluetooth ->
                Log.d(
                    TAG,
                    "已配对的蓝牙设备名称：${bluetooth.name}," +
                            "已配对的蓝牙设备类型：${bluetooth.type}," +
                            "已配对的蓝牙设备地址：${bluetooth.address}," +
                            "已配对的蓝牙uuid：${bluetooth.uuids}"
                )
                //连接所有已经配对的
                connectBlueTooth(bluetooth)
            }
        } else {
            Log.d(
                TAG,
                "蓝牙打开失败"
            )

        }
    }

    private fun connectBlueTooth(device: BluetoothDevice) {
        //如果传null，默认使用{@link #SPP_UUID}连接
        BTManager.getInstance().createConnection(device, this) //观察者监听连接状态
            ?.connect(null, object : ConnectCallback {
                override fun onSuccess() {
                    Log.d(
                        TAG,
                        "蓝牙连接成功"
                    )
                }

                override fun onFail(errMsg: String, e: Throwable?) {
                    Log.d(
                        TAG,
                        errMsg
                    )

                }
            })

    }

    /**
     * 监听蓝牙状态改变
     */
    override fun onConnectionStateChanged(device: BluetoothDevice, state: Int) {
        super.onConnectionStateChanged(device, state)
        Log.d(
            TAG,
            "蓝牙连接状态：${state}," +
                    "蓝牙设备名称：${device.name}," +
                    "蓝牙设备类型：${device.type}," +
                    "蓝牙设备地址：${device.address}," +
                    "uuid：${device.uuids.size}"
        )

        when (state) {
            Connection.STATE_CONNECTING -> {

            }
            Connection.STATE_PAIRING -> {

            }
            Connection.STATE_PAIRED -> {
                //配对完成之后，连接蓝牙
                connectBlueTooth(device)
            }
            Connection.STATE_CONNECTED -> {

            }
            Connection.STATE_DISCONNECTED -> {
                //断开重连
                connectBlueTooth(device)
            }
            Connection.STATE_RELEASED -> {

            }
        }
    }

    /**
     * 接收蓝牙设备数据
     */
    override fun onRead(device: BluetoothDevice, value: ByteArray) {
        super.onRead(device, value)
        when (device.name.contains("BarCode Scanner")) {
            true -> {
                barCode.append(String(value))
                if (value[value.size-1].toInt() == 13)//以回车结束
                {
                    Log.d(
                        TAG, "barCode=${barCode}"
                    )
                    findViewById<TextView>(R.id.textview_wasteNo).text = barCode
                    barCode.setLength(0)
                }

            }
            else -> {
                val weight = String(value).replace("\r\n", "")
                findViewById<TextView>(R.id.textview_weight).text = weight
            }
        }


    }

    /**
     * 2.4G模式 和 HID模式的扫码枪会调用此方法
     */
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {



        Log.d(
            TAG, "747273183：${event.toString()}"
        )

        val deviceName = InputDevice.getDevice(event.deviceId).name
        if ( deviceName.contains(BARCODE_SCANNER_HID) || deviceName.contains(BARCODE_SCANNER_HID0581)) {
            if (event.action == ACTION_DOWN) {
                if (event.keyCode != KEYCODE_ENTER) {
                    //如果是可见字符才拼接进去
                    if (event.unicodeChar !in 0..31 && event.unicodeChar != 127) {
                        barCode.append(event.unicodeChar.toChar())
                    }

                } else {
                    Log.d(
                        TAG, "扫码结果,barCode=${barCode}"
                    )

                    val isLegal = regex.matches(input = barCode)
                    if (isLegal) {
                        val wasteNumber = barCode.split("=")[1]

                        Log.d(
                            TAG, "wasteNumber=$wasteNumber"
                        )
                        findViewById<TextView>(R.id.textview_wasteNo).text = wasteNumber

                    } else {

                        Toast.makeText(this, "无效码", Toast.LENGTH_SHORT).show()
                        Log.d(
                            TAG, "无效码,newBarCode=${barCode}"
                        )
                    }

                    barCode.setLength(0)

                }

            }
            return true //不往下传递
        } else {

            return super.dispatchKeyEvent(event)
        }


    }




}




